<?php

namespace app\common\model;

use basic\ModelBasic;

use app\common\model as M;
class Package extends ModelBasic
{
	use \traits\ModelTrait;

    //1永久 2：指定日期
    public static $expire_type = [
        1    =>    '永久有效',
        2    =>    '指定日期',
    ];

    public static $valid_type = [
        1    =>    '单项计次',
        2    =>    '整体计次',
        3    =>    '不限次数',
    ];

	 /**
     * 列表
     * @Author   FW
     * @DateTime 2020-09-24
     * @Email    123763712@qq.com
     * @param    [type]
     * @return   [type]
     */
    public static function getList($where){
        $count = self::setWhere($where)->count();
        $data  = [];
        if ( $count == 0 ) {
            return compact('data','count');
        }

        $data=self::setWhere($where,'m')
        ->field('m.*,org.organ_name,sch.school_name,ifnull(sp.is_open,0) as sp_is_open,sp.share_poster')
        ->join('__ORGAN__ org','m.org_id=org.id' , 'left')
        ->join('__SCHOOL__ sch','m.school_id=sch.id' , 'left')
        ->join('__DISTRIBUTION_SEPARATE__ sp',sprintf('m.id=sp.relation_id AND sp.relation_type=%d',DistributionSeparate::REL_TYPE_PACKAGE) , 'left')
        ->page($where['page'] ?? 1,$where['limit'] ?? 10)
        ->select();

        if ( !empty($data) ) {
            $data = $data->toArray();
            $data = static::process_list($data);
        }

        return compact('data','count');
    }

    /**
     * [getOne description]
     * @Author   FW
     * @DateTime 2021-01-12
     * @Email    123763712@qq.com
     * @param    [type]           $id [description]
     * @return   [type]               [description]
     */
    public static function getOne ($id)
    {
        $item = self::alias('m')->where('m.id',$id)
            ->field("m.*,org.organ_name,sch.school_name,ifnull(sp.is_open,0) as sp_is_open,sp.share_poster,ifnull(pink.status,0) as pink_is_open,ifnull(pink.pink_price,0) as pink_price,ifnull(pink.pink_nums,0) as pink_nums,ifnull(pink.start_time,'') as pink_start_time,ifnull(pink.end_time,'') as pink_end_time")
            ->join('__ORGAN__ org','m.org_id=org.id' , 'left')
            ->join('__SCHOOL__ sch','m.school_id=sch.id' , 'left')
            ->join('__DISTRIBUTION_SEPARATE__ sp',sprintf('m.id=sp.relation_id AND sp.relation_type=%d',DistributionSeparate::REL_TYPE_PACKAGE) , 'left')
            ->join('__PINK_CONFIG__ pink',"m.id=pink.rel_id AND pink.rel_type='package' AND pink.status=1" , 'left')
            ->find();

        if ( empty($item) ) {
            return [];
        }

        $item = $item->toArray();

        $item['detail'] = htmlspecialchars_decode(CommonDetail::where(['rel_type'=>'package','rel_id'=>$item['id']])->value('detail'));

        $item['items']  = PackageItems::where('pck_id',$item['id'])->select();

        return static::process_list([$item])[0];
    }

     /**
     * 处理列表数据
     * @Author   FW
     * @DateTime 2021-01-12
     * @Email    123763712@qq.com
     * @param    array            $list [description]
     * @return   [type]                 [description]
     */
    public static function process_list (array $list)
    {
        foreach ($list as $key => &$value) {
            $value['price'] *= 1;
            $value['original_price'] *= 1;

            $value['status_text']      = static::$common_status[$value['status']] ?? '-';

            $value['expire_type_display'] = static::$expire_type[$value['expire_type']] ?? '-';
            $value['valid_type_display']  = static::$valid_type[$value['valid_type']] ?? '-';
            $value['expire_time'] = date('Y-m-d' , strtotime($value['expire_time']));
            $value['cover'] = json_decode($value['cover']);
        }
        return $list;
    }

	/**
	 * 设置where条件
	 * @Author   FW
	 * @DateTime 2021-01-12
	 * @Email    123763712@qq.com
	 * @param    [type]           $where [description]
	 * @param    string           $alias [description]
	 * @param    [type]           $model [description]
	 */
	public static function setWhere($where,$alias='m',$model=null){
        $model = $model===null ? new self() : $model;

        $model->alias($alias);

        if ( isset($where['org_id']) && $where['org_id'] > 0 ) {
            $org_id = $where['org_id'] + 0;
        } else {
            $org_id = static::getBelongOrganId();
        }
        if ( $org_id > 0 ) {
            $model->where(sprintf('%s.org_id=%d' , $alias , $org_id));
        }

        if ( isset($where['school_id']) && $where['school_id'] > 0 ) {
            $school_id = $where['school_id'] + 0;
        } else {
            $school_id = static::getBelongSchoolId();
        }

        if ( $school_id > 0 ) {
            $model->where($alias.'.school_id',$school_id);
        }

        if ( static::$softDelete ) {
        	$model->where($alias.'.is_del',0);
        }

        if ( isset($where['name']) && $where['name'] != '' ) {
            $model->where( sprintf('%s.name' , $alias) . ' LIKE ' . "'%" . $where['name'] ."%'");
        }

        /** 选择用户已购 用户已购怎么在这里选择呢？*/
        if ( isset($where['uid']) && $where['uid'] > 0 ) {
            // $model->where(sprintf("%s.id IN (SELECT pck_id FROM eb_bought_package WHERE uid = %d AND status = 1)" , $alias, $where['uid']));
        }

        // 推荐至首页
        if ( isset($where['is_rmt']) && $where['is_rmt'] > 0 ) {
             $model->where(sprintf('%s.is_rmt=1' , $alias , $org_id));
        }

        if ( isset($where['order']) && $where['order'] != '' ) {
            $model->order(sprintf('%s.%s' , $alias, $where['order']));
        } else {
            $model->order(sprintf('%s.id DESC' , $alias));
        }

        return $model;
    }

    /**
     * 主数据保存后回调
     * @Author   FW
     * @DateTime 2021-08-10
     * @Email    123763712@qq.com
     * @param    [type]           $prk_id [description]
     * @param    array            $data   [description]
     * @return   [type]                   [description]
     */
    public static function afterSave ( $prk_id , array $data )
    {
        /**
         * 保存套餐详情
         */
        if ( isset($data['detail']) ) {
            $res = CommonDetail::saveOne([
                'rel_type'    =>    'package',
                'rel_id'      =>    $prk_id,
                'detail'      =>    htmlentities($data['detail'])
            ]);

            if ( $res === false ) return false;
        }

        /**
         * 保存套餐子项
         * @notes 前台新增、编辑子项时，如果新增则不存在子项ID，直接DOM删除，如果编辑则存在子项ID，直接通过接口删除
         */
        if ( isset($data['items']) ) {
            $allowFields = [];
            foreach ( $data['items'] as $item ) {
                $allowFields[] = [
                    'id'         => $item['id'] ?? 0,
                    'pck_id'     => $prk_id,
                    'rel_type'   => $item['rel_type'] ?? '',
                    'rel_name'   => $item['rel_name'] ?? '',
                    'rel_id'     => $item['rel_id'] ?? 0,
                    'price'      => $item['price'] ?? 0,
                    'valid_nums' => $item['valid_nums'] ?? 0,
                ];
            }
            $res = PackageItems::batchSave($allowFields);
            if ( $res === false ) return false;
        }

        return true;
    }

    /**
     * 选择已购套餐预检查以及返回正确数据格式
     * @Author   FW
     * @DateTime 2021-08-11
     * @Email    123763712@qq.com
     * @param    [type]           $id [description]
     */
    public static function ConsumePrecheck ( $pck_id , $bought_id = 0 )
    {
        if ( $bought_id > 0 ) {
            $package = BoughtPackage::alias('b')
            ->field('b.pck_id,b.pck_name,0 as price,b.expire_type,b.expire_time,b.valid_type,b.valid_nums,b.used_nums,(b.valid_nums - b.used_nums) as max_nums,b.bought_qty as qty')
            ->where(['b.id' => $bought_id, 'b.status' => 1])
            ->find();

            $package_items = M\user\BoughtPackageItems::field("pck_id,rel_type,rel_id,rel_name,0 as price,1 as qty,(valid_nums - used_nums) as max_nums,100 as discount,0 as disc_amt,bought_id")
            ->where(['pck_id' => $pck_id , 'bought_id' => $bought_id])
            ->where('valid_nums > used_nums')
            ->select()
            ->toArray();

        } else {
            $package = Package::alias('pck')
            ->field('pck.id as pck_id,pck.price,pck.name as pck_name,pck.expire_type,pck.expire_time,pck.valid_type,pck.valid_nums,0 as used_nums,999 as max_nums,1 as qty')
            ->where('id' , $pck_id)
            ->find();

            $package_items = PackageItems::field('pck_id,rel_type,rel_id,rel_name,price,1 as qty,valid_nums as max_nums,100 as discount,0 as disc_amt')
            ->where('pck_id',$package->pck_id)
            ->select()
            ->toArray();
        }

        if ( empty($package) ) throw new \think\exception\ValidateException('校验失败【0901】');

        $valid['item_ukey'] = md5('package_' . $package->pck_id . '_' . $bought_id);
        $valid['pck_id']    = $package->pck_id;
        $valid['bought_id'] = $bought_id;
        $valid['price']     = $package->price;
        $valid['discount']  = 100;
        $valid['disc_amt']  = 0;
        $valid['max_nums']  = $package->max_nums;
        $valid['pck_name']  = $package->pck_name;
        $valid['qty']       = $package->qty;
        $valid['valid_type']= $package->valid_type;
        $valid['valid_nums']= $package->valid_nums;
        $valid['expire_type']= $package->expire_type;
        $valid['expire_time']= $package->expire_time;

        // 指定日期有效
        if ( $package->expire_type == 2 ) {
            if ( strtotime($package->expire_time) < time() ) {
                throw new \think\exception\ValidateException('已过期');
            }
        }

        // 整体计次时
        if ( $package->valid_type == 2 ) {
            if ( $valid['max_nums'] <= 0 ) {
                throw new \think\exception\ValidateException('已使用完');
            }
        }

        foreach ( $package_items as &$item ) {
            ## 整体计次的套餐，子项单次最大可用数等于整体次数 => 1
            if ( $package->valid_type == 2 ) {
                 $item['max_nums'] = 1;
            }

            ## 不限次数的套餐，子项单次最大可用数设为99
            if ( $package->valid_type == 3 ) {
                 $item['max_nums'] = 999;
            }
        }
        $valid['packages'] = $package_items;
        return $valid;
    }
}//Class End
